<template>
  <div class="cpro-logo">
    <cpro-public title="Logo（可不选）">
      <div class="logo">
        <el-upload
          v-model:file-list="fileList"
          action="#"
          list-type="picture-card"
          :auto-upload="false"
          :on-change="getFile"
          limit="1"
        >
          <el-icon><Plus /></el-icon>
          <template #file="{ file }">
            <div>
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt="#" />
              <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-delete" @click="handleRemove()">
                  <el-icon><Delete /></el-icon>
                </span>
              </span>
            </div>
          </template>
        </el-upload>
      </div>
    </cpro-public>
  </div>
</template>

<script lang="ts" setup>
import cproPublic from '@/components/creat-projects/cpro-public.vue'
import { computed, ref, watchEffect } from 'vue'
import type { UploadFile, UploadUserFile } from 'element-plus'
import { ElMessage } from 'element-plus'
import { Delete, Plus } from '@element-plus/icons-vue'

const emit = defineEmits(['upLoadLogo'])
const fileList = ref<UploadUserFile[]>([])
const logo = new FormData()
const isFileReady = computed(() => fileList.value.length > 0)
//移除文件
const handleRemove = () => {
  fileList.value.splice(0, 1)
}
//获取上传的文件
const getFile = async (file: UploadFile) => {
  if (fileList.value.length < 1) {
    fileList.value.push({ name: file.name, url: file.url })
    logo.append('file', file.raw as Blob, file.name)
    emit('upLoadLogo', logo)
  }
  if (!file.raw?.type.includes('image')) {
    ElMessage.error('只能上传图片文件')
    handleRemove()
  }
  if (file.size && file.size / 1024 / 1024 > 5) {
    ElMessage.error('上传图片大小不能超过 5MB')
    handleRemove()
  }
}
//当isFileReady为true时.el-upload--picture-card设置为display: none
watchEffect(() => {
  if (isFileReady.value) {
    document.querySelector('.el-upload--picture-card')?.setAttribute('style', 'display: none')
  } else {
    document
      .querySelector('.el-upload--picture-card')
      ?.setAttribute('style', 'display: inline-flex')
  }
})
</script>

<style lang="less" scoped>
.logo {
  margin: 20px 8px;
}
/deep/ .el-upload--picture-card {
  width: 160px;
  height: 90px;
}
/deep/ .el-upload-list__item {
  width: 160px;
  height: 90px;
}
/deep/ .el-upload-list__item-thumbnail {
  width: 160px;
  height: 90px;
  object-fit: cover;
}
</style>
